//工具函数

const api = require('./api.js');
const util = require('./util.js');

//获取formId
function saveFormId(e) {
    var that = this;
    var formIdList = [];
    var time = new Date().getTime();
    // console.log('表单数据', e);
    //获取缓存中的formId
    wx.getStorage({
        key: 'formId',
        success: function(res) {
            console.log('缓存中的formId', res.data)
            formIdList = res.data || [];
        },
        fail: function(err) {
            console.log('缓存中没找到formId', err)
        },
        complete: function() {
            formIdList.push({
                formId: e.detail.formId,
                currentTime: Math.floor(time / 1000),
                expireTime: Math.floor(time / 1000) + 604800
            });
            wx.setStorage({
                key: "formId",
                data: formIdList
            })
        }
    })
}

//判断微信sdk版本
function judgeSDKVersion(v) {
    if (v < 160) {
        wx.showModal({
            title: '提示',
            content: '当前微信版本过低，部分功能可能无法使用，建议升级到最新微信版本后重试。',
            showCancel: false,
            success: function(res) {
                if (res.confirm) {
                    return;
                }
            }
        })
        return;
    }
}
//获取token
function functiongetToken(self) {
    // var address = 'http://ies.acadsoc.com.cn/ECI/kouyuxiu/ies_base.ashx';
    var address = 'http://192.168.74.98:8085/ECI/kouyuxiu/ies_base.ashx';
    var AppKey = '049BD15C6FC04BD80808A601DC46E50515CBEEA33FB29AB4';
    var appid = 'wxa7a974760bbe6c7f';
    var secret = '79e0512dee75f1dffa42474885e14fcd';
    var url = `${address}?AppKey=${AppKey}&appid=${appid}&secret=${secret}&action=GetWechatToken`;
    wx.request({
        url: url,
        data: {},
        header: {
            'content-type': 'application/json' // 默认值
        },
        method: 'GET',
        success: function(res) {
            console.log('获取token请求成功', res)
            self.globalData.access_token = res.data.data.access_token;
        },
        fail: function(err) {
            console.log('获取token请求错误', err)
        },
        complete: function() {
            // console.log(self.globalData.access_token)
        }
    })

}
//绘制倒计时效果
function countDown(params, RemainingTime, scale) {
    console.log('播放倒计时效果');
    var ctx_gray = wx.createCanvasContext('canvas-gray');

    var radius = 25

    //保证小屏幕能够完全显示出来
    if (scale < 0.9) {
        radius = 19
    }

    //画灰色的圆弧
    ctx_gray.setLineWidth(10);
    ctx_gray.arc(33, 35, radius, -0.5 * Math.PI, 1.5 * Math.PI)
    ctx_gray.setStrokeStyle('#dcdcdc');
    ctx_gray.stroke();
    ctx_gray.draw(true);

    var ctx_red = wx.createCanvasContext('canvas-red');
    var time = RemainingTime * 1000;
    var space = 50; //时间间隔，毫秒
    // var step = 2 * Math.PI * space * 0.32 / time; //移动步长
    var bili = 20 * time / 1000;
    var step = 2 * Math.PI / bili;
    var totalTime = 0; //花费的总时间
    var totalStep = 0; //走过的总步长

    var timer_daojishi = setInterval(function() {
        totalStep += step;
        totalTime += space;
        ctx_red.setLineWidth(10);
        ctx_red.setLineCap('round');
        drawcircle(ctx_red, totalStep, radius);
        if (totalTime >= time) {
            clearInterval(timer_daojishi);
            //倒计时结束清除画布
            ctx_gray.clearRect(0, 0, 140, 140);
            ctx_gray.draw(true);
            ctx_red.clearRect(0, 0, 140, 140);
            ctx_red.draw(true);
            return;
        }
    }, space)

    //画弧函数
    function drawcircle(ctx, step, radius) {
        ctx.arc(33, 35, radius, -0.5 * Math.PI, -0.5 * Math.PI + step);
        ctx.setStrokeStyle('#3DBF8F');
        ctx.stroke();
        ctx.draw(true);
    }
}

//试听计时效果
function listenTimeKeeping (param) { 
    
}
//获取小程序码
function getWxCode(obj, resolve, reject) {
    var that = this;
    var data = {
        scene: obj.scene,
        path: obj.page || 'pages/index/index',
        width: obj.width || 430,
        auto_color: obj.auto_color || false,
        line_color: obj.line_color || JSON.stringify({ "r": "0", "g": "0", "b": "0" })
    }
    console.log('获取小程序码data', data)
    api.methodGetWxaCode({
        method: 'POST',
        dataDic: data,
        contentType: 'application/x-www-form-urlencoded',
        success: (res) => {
            if (res.data.data.indexOf('http') == -1) {
                console.log('获取小程序码失败', res.data.data);
                typeof reject == 'function' && reject(res);
            } else {
                console.log('获取小程序码成功', res);
                typeof resolve == 'function' && resolve(res);
            }
        },
        fail: (err) => {
            console.log('获取小程序码失败', err);
            typeof reject == 'function' && reject(err);
        }
    })
}

//获取练习次数
function getPracticeTimes(params, cb) {
    console.log('获取练习次数');

    api.methodGetChallengeCount({
        dataDic: {
            OpenId: params.OpenId,
            UID: params.UID
        },
        complete: function(res) {
            console.log('获取练习次数完成', res);
            typeof cb == 'function' && cb(res);
        }
    })
}
//计时时间转为时间格式
function timeFormat (param) { 
    var M = util.formatNumber(Math.floor(param / (60)) % 60);
    var S = util.formatNumber(Math.floor(param) % 60);
    var text = M + ":" + S;
    return text;
}
module.exports = {
    saveFormId,
    judgeSDKVersion,
    functiongetToken,
    countDown,
    getWxCode,
    getPracticeTimes,
    timeFormat
}